var request = require('../../utils/https.js');
var uri = 'cart/check.html';
var pay='cart/pay.html'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts: [],
    addressList:{},
    totalPrice: 0,           // 总价，初始为0
    totalCount: 0, 
  },
  /**
   * 下单
   */
  order:function(){
    if (this.data.addressList.user_id!= undefined){
      var type = wx.getStorageSync('userType');
      if (type == 2 || type == 5) {
        wx.navigateTo({
          url: '../orderInfo/orderInfo',
        })
      } else {
        request.req(pay,
          { user_id: wx.getStorageSync('userId') },
          (err, res) => {
            var data = res.data;
              wx.requestPayment({
                'timeStamp': '',
                'nonceStr': '',
                'package': '',
                'signType': 'MD5',
                'paySign': '',
                'success': function (res) {
                  console.log(res);
                },
                'complete ':function(res){
                   console.log(res);
                },
                'fail': function (res) {
                  console.log(res);
                }
              })
          })
      }
    }else{
      wx.showToast({
        title: '请添加收货地址',
        icon: 'none',
      })
    }
    
  },
  /**
   * 计算总价
   */
  getTotalPrice() {
    let carts = this.data.carts;                 // 获取购物车列表
    let count = 0;                               // 获取购物车产品数量
    let total = 0;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].status) {                     // 判断选中才会计算价格
        total += carts[i].number * carts[i].unit_price;   // 所有价格加起来
        count += carts[i].number;                           // 所有数量加起来
      }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2),
      totalCount: count
    });
  },
  /**
   * 获取页面数据
   */
  getData:function(){
      var that=this;
      request.req(uri,
       {user_id:wx.getStorageSync('userId')},
       (err,res)=>{
          var data=res.data;
          that.setData({
            addressList:data.address_info,
            carts: data.deal_list
          })
          that.getTotalPrice();
       })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
  },
})